<template>
  <div class="m-user-table">
    <div class="header">
      <el-form :inline="true" :model="queryParams" ref="ruleFormRef" class="text-bold">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="queryParams.phonenumber" placeholder="请输入要搜索的手机号"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="状态"
            clearable
            @keyup.enter.native="getUserListPage"
          >
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserListPage" icon="Search">查询</el-button>
          <el-button icon="Refresh" @click="reset(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="footer">
      <div class="util">
        <el-button
          type="primary"
          icon="Plus"
          @click="addHandler"
          v-hasPermi="['system:user:add']"
        >
          新增
        </el-button>
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
        >导出
        </el-button>
        <el-button
          type="info"
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入
        </el-button
        >
        <el-button
          type="danger"
          icon="Delete"
          @click="handleDelete(ids)"
          v-hasPermi="['system:user:remove']"
          :disabled="multiple"
        >批量删除
        </el-button
        >
      </div>
      <div class="table-inner">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%; height: 100%"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center"></el-table-column>
          <el-table-column prop="userId" label="用户ID" align="center"></el-table-column>
          <el-table-column
            prop="username"
            label="用户名"
            align="center"
            how-overflow-tooltip
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="nickName"
            label="昵称"
            align="center"
            how-overflow-tooltip
            :show-overflow-tooltip="true"
          />
          <el-table-column prop="sex" label="性别" align="center" width="60">
            <template #default="scope">
              <div v-for="item in dict.type.sys_user_sex">
                {{ item.value == scope.row.sex ? item.label : "" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="roles"
            label="关联角色"
            align="center"
            how-overflow-tooltip
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <el-tag size="small" type="success" v-for="item in scope.row.roleList">
                {{ item.roleName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="phonenumber" label="手机号" align="center" width="120" />
          <el-table-column prop="status" label="用户状态" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                @change="handleStatusChange(scope.row)"
                active-value="0"
                inactive-value="1"
                active-color="#599e5e"
                inactive-color="red"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            :show-overflow-tooltip="true"
            width="150"
            label="用户描述"
            align="center"
          />
          <el-table-column prop="createTime" label="创建时间" align="center" width="180" />
          <el-table-column prop="operator" label="操作" width="250px" align="center" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="editHandler(scope.row)"
                v-hasPermi="['system:user:edit']"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="handleDelete(scope.row.userId)"
                v-hasPermi="['system:user:remove']"
              >
                删除
              </el-button>

              <el-dropdown
                size="large"
                placement="bottom-end"
                style="margin-left: 10px"
                v-hasPermi="['system:user:resetPwd', 'system:user:edit']"
              >
                <el-button type="warning" size="small" icon="DArrowRight">更多</el-button>
                <template #dropdown>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      @click="handleResetPwd(scope.row)"
                      icon="Key"
                      v-hasPermi="['system:user:resetPwd']"
                    >
                      重置密码
                    </el-dropdown-item>
                    <el-dropdown-item
                      icon="CircleCheck"
                      v-hasPermi="['system:user:edit']"
                      @click="handleAuthRole(scope.row)"
                    >
                      分配角色
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <!--分页器            -->
        <el-pagination
          v-show="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[5, 10, 15, 20, 25, 30]"
          :background="true"
          layout="prev, pager, next, jumper, ->,  sizes, total"
          :total="total"
          @current-change="getList"
          @size-change="getList"
        />
      </div>
    </div>

    <userDialog ref="userDialogRef" @getList="getList" />
    <importDialog ref="importDialogRef" @getUserListPage="getList" />
  </div>
</template>
<script lang="ts" setup>
import { ElMessageBox, FormInstance } from "element-plus";
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import {
  reqResetPwd,
  reqUserChangeStatusUrl,
  reqUserDeleteUrl,
  reqUserPageUrl
} from "@/api/system/user";
import userDialog from "../components/userDialog.vue";

const tableData = ref();
const dialogVisible = ref(false);
const userDialogRef = ref();
const importDialogRef = ref();
const ruleFormRef = ref<FormInstance>();
const queryParams = reactive({
  pageNum: 1 /*第几页*/,
  pageSize: 10 /*一页几个数据*/,
  username: undefined /*用户名*/,
  phonenumber: undefined /*手机号*/,
  deptId: undefined, // 部门编号
  status: undefined /*用户状态*/,
  beginTime: undefined /*开始时间*/,
  endTime: undefined /*结束时间*/
});
const dateRange = ref([]); //创建的范围

const loading = ref(true);
const { proxy }: any = getCurrentInstance();
const total = ref(0); /*总计*/
const ids = ref([]); // 选中数组
const single = ref(true); // 非单个禁用
const multiple = ref(true); //多个开启
const $router = useRouter();

/*多选框*/
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

//分页查询
const getUserListPage = async () => {
  queryParams.pageNum = 1;
  await getList();
};

const getList = async () => {
  loading.value = true;
  queryParams.beginTime = dateRange.value[0];
  queryParams.endTime = dateRange.value[1];
  await reqUserPageUrl(queryParams).then((req: reqTableData) => {
    if (req.code == 200) {
      tableData.value = req.rows;
      total.value = req.total;
    } else {
      proxy.$modal.msgError(req.message);
    }
  }).catch((e) => {});
  loading.value = false;
  queryParams.beginTime = null;
  queryParams.endTime = null;
};

//重置按钮
const reset = (formEl: FormInstance | undefined) => {
  // 将信息都进行重置
  formEl.resetFields();
  Object.keys(queryParams).forEach((key) => {
    if (key === "pageNum") {
      queryParams[key] = 1;
    } else if (key === "pageSize") {
      queryParams[key] = 10;
    } else {
      queryParams[key] = null;
    }
  });
  dateRange.value[0] = null;
  dateRange.value[1] = null;
  getUserListPage();
};

// 添加用户
const addHandler = () => {
  userDialogRef.value.show();
};

// 修改用户
const editHandler = (row) => {
  userDialogRef.value.show(row);
};

// 删除用户
const handleDelete = (userIds: any) => {
  ElMessageBox.confirm("你确定要删除" + userIds + "项吗?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      // 进行删除操作
      console.log(userIds);
      await reqUserDeleteUrl(userIds).then((req) => {
        if (req.code == 200) {
          proxy.$modal.msgSuccess("删除成功");
          // 进行刷新
          getUserListPage();
        } else {
          proxy.$modal.msgSuccess("删除失败");
          console.log(req.message);
        }
      });
    })
    .catch((e) => {
      console.log("删除用户", e.message);
    });
};

// 导出用户
const handleExport = () => {
  // 调用接口
  proxy.$download("system/user/export", { ...queryParams }, `user_${new Date().getTime()}.xlsx`);
};
// 导入用户
const handleImport = () => {
  importDialogRef.value.show();
};

/**
 * 状态修改
 * @param row
 */
const handleStatusChange = (row) => {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm("确认要\"" + text + "\"\"" + row.username + "\"用户吗？")
    .then(async () => {
      await reqUserChangeStatusUrl({ userId: row.userId, status: row.status })
        .then((req: any) => {
          if (req.code === 200) {
            proxy.$modal.msgSuccess(text + "成功!");
          } else {
            proxy.$modal.msgError(text + "失败！" + req.message);
            row.status = !row.status;
          }
        })
        .catch(() => {
          row.status = !row.status;
        });
    })
    .catch(() => {
      row.status = !row.status;
    });
};

/*重置密码---密码验证规则*/
const passwordRegex = /^(.{8,24})$/;

// 重置密码
const handleResetPwd = (row: any) => {
  /*弹出对话框*/
  ElMessageBox.prompt(`请输入'${row.username}'用户的新密码:`, "修改密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: passwordRegex,
    inputErrorMessage: "密码8~24为任意字符"
  })
    .then(async (value: any) => {
      const from = {
        userId: row.userId,
        newPassword: value.value
      };
      /*将新的密码传递到服务器进行设置*/
      await reqResetPwd(from).then((req) => {
        if (req.code === 200) {
          proxy.$modal.msgSuccess("修改成功！");
        } else {
          proxy.$modal.msgError("修改失败！");
        }
      });
    })
    .catch(() => {
    });
};

// 分配用户
const handleAuthRole = (row: any) => {
  const userId = row.userId;
  $router.push("/system/user-auth/role/" + userId);
};

import $bus from "@/bus";
import { useRouter } from "vue-router";
import ImportDialog from "@/views/system/user/components/importDialog.vue";
import { reqTableData } from "@/api/type";
import DictTag from "@/components/DictTags/index.vue";

onMounted(async () => {
  loading.value = true;
  await getUserListPage(); //获取第一页数据
  setTimeout(() => {
    loading.value = false;
  }, 1000);

  // 绑定一个事件接收兄弟组件传来的数据
  // 第一个参数是事件的类型，第二个参数是事件的回调
  $bus.on("deptId", async (deptId) => {
    console.log(deptId.deptId);
    queryParams.deptId = deptId.deptId;
    queryParams.pageNum = 1;
    await getUserListPage(); //获取第一页数据
  });
});
</script>

<script lang="ts">
export default {
  dicts: ['sys_normal_disable', 'sys_user_sex'],
}
</script>

<style lang="scss" scoped>
@import '../index';
</style>
